package com.lyh.notes.controller;

import com.lyh.notes.model.base.ApiResponse;
import com.lyh.notes.model.base.EmptyVO;
import com.lyh.notes.model.dto.user.LoginRequest;
import com.lyh.notes.model.dto.user.RegisterRequest;
import com.lyh.notes.model.dto.user.UpdateUserRequest;
import com.lyh.notes.model.dto.user.UserQueryParam;
import com.lyh.notes.model.entity.User;
import com.lyh.notes.model.vo.user.*;
import com.lyh.notes.service.UserService;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import javax.validation.constraints.Min;
import javax.validation.constraints.Pattern;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api")
public class UserController {

    @Autowired
    UserService userService;

    @PostMapping("/users")
    public ApiResponse<RegisterVO> register(
            @Valid
            @RequestBody
            RegisterRequest registerRequest) {
        return userService.register(registerRequest);
    }

    @DeleteMapping("/admin/users/{userId}")
    public ApiResponse<EmptyVO> deleteUser(
            @PathVariable
            @Pattern(regexp = "\\d+", message = "ID 格式错误")
            Long userId) {
        return userService.deleteUser(userId);
    }

    @PostMapping("/users/login")
    public ApiResponse<LoginUserVO> login(
            @Valid
            @RequestBody
            LoginRequest loginRequest){
        return userService.login(loginRequest);
    }

    @PostMapping("/users/whoami")
    public ApiResponse<LoginVO> whoami(){
        return userService.whoAmI();
    }

    @GetMapping("/users/{userId}")
    public ApiResponse<UserVO> queryUser(
            @PathVariable
            @Pattern(regexp = "\\d+", message = "ID 格式错误")
            Long userId){
        return userService.getUserInfo(userId);
    }

    @PatchMapping("/users/me")
    public ApiResponse<EmptyVO>updateUserInfo(@Valid @RequestBody UpdateUserRequest updateUserRequest){
        return userService.updateUserInfo(updateUserRequest);
    }

    @PostMapping("/users/avatar")
    public ApiResponse<AvartarVO> uploadAvatar(
            @RequestParam("file") MultipartFile file){
        return userService.uploadAvatar(file);
    }

    @GetMapping("/admin/users")
    public ApiResponse<List<User>> adminGetUser(
            @Valid UserQueryParam queryParam) {
        return userService.getUserList(queryParam);
    }
}
